<template>
  <div class="menu">
    <el-row>
      <el-col :xs="24" :lg="8">
        <el-card class="box-card left">
          <el-tree
            :data="tree.data"
            ref="tree"
            node-key="id"
            @node-click="treeClick"
            :default-expanded-keys="['app' + USER.app.id]"
            accordion
            :render-content="treeContent">
          </el-tree>
          <div style="margin-top: 5px">
            <span style="width: 100px;display: inline-block">调整菜单</span>
            <el-switch
              v-model="menuUpdate"
              on-text="开"
              off-text="关"
              on-color="#13ce66"
              off-color="#ff4949">
            </el-switch>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="16">
        <el-card class="box-card right">
          <div slot="header" class="clearfix">
            <span style="line-height: 36px;"> {{tree.select.menuName || '菜单'}} 详情</span>
            <el-button style="float: right;" type="primary" v-if="tree.select.id !== 0" @click="dialogOpen('PUT')">修改</el-button>
          </div>
          <el-form :model="tree.select" labelWidth="80px" label-position="left" v-if="tree.select.id !== 0">
            <el-row>
              <el-col :xs="24" :lg="{span: 10, offset: 0}">
                <el-form-item prop="menuName" label="菜单名称"><span>{{tree.select.menuName}}</span></el-form-item>
                <el-form-item prop="menuName" label="菜单级别"><span>{{tree.select.menuLevel}}</span></el-form-item>
                <el-form-item prop="openTarget" label="页面位置"><span>{{tree.select.show_openTarget}}</span></el-form-item>
                <el-form-item prop="menuType" label="菜单类型"><span>{{tree.select.show_menuType}}</span></el-form-item>
                <el-form-item prop="menuType" label="菜单图标"><span>{{tree.select.img}}</span></el-form-item>
              </el-col>
              <el-col :xs="24" :lg="{span: 10, offset: 2}">
                <el-form-item prop="menuCode" label="菜单编码"><span>{{tree.select.menuCode}}</span></el-form-item>
                <el-form-item prop="isShow" label="显示状态"><span>{{tree.select.isShow === 1?'显示':'隐藏'}}</span></el-form-item>
                <el-form-item prop="description" label="菜单描述"><span>{{tree.select.description}}</span></el-form-item>
                <el-form-item prop="description" label="链接地址"><span>{{tree.select.navigateUrl}}</span></el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <p v-else>点击菜单树，查看详情</p>
        </el-card>
      </el-col>
    </el-row>

    <s-dialog :dialog="dialog" :close="dialogInit">
      <p slot="title">{{dialog.title}}<span>菜单级别： {{formDialog.menuLevel}} 级菜单</span></p>
      <s-form :form="formDialog" ref="formDialog">
        <el-row>
          <el-col :xs="24" :lg="{span: 10, offset: 0}">
            <el-form-item prop="menuName" label="菜单名称">
              <el-input type="text"
                        v-model="formDialog.menuName"
                        placeholder="菜单名称" spellcheck="false" auto-capitalize="off" auto-complete="off" auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 10, offset: 2}">
            <el-form-item prop="menuCode" label="菜单编码">
              <el-input type="text"
                        v-model="formDialog.menuCode"
                        placeholder="菜单编码" spellcheck="false" auto-capitalize="off" auto-complete="off" auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 10, offset: 0}">
            <el-form-item prop="parent" label="上级菜单">
              <div class="s-content">
                <el-tag type="success">{{formDialog.parent||'顶级菜单'}}</el-tag>
              </div>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 10, offset: 2}">
            <el-form-item prop="menuType" label="菜单类型">
              <el-select v-model="formDialog.menuType" filterable placeholder="请选择">
                <el-option
                  v-for="item in MENU.menuType"
                  :key="item.dictionaryid"
                  :label="item.value"
                  :value="item.dictionaryid">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 10, offset: 0}">
            <el-form-item prop="isShow" label="显示状态">
              <div class="s-content">
                <el-switch
                  off-text="隐藏"
                  on-text="显示"
                  v-model="formDialog.isShow"
                  on-color="#13ce66"
                  off-color="#ff4949">
                </el-switch>
              </div>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 10, offset: 2}">
            <el-form-item prop="menuType" label="页面位置">
              <el-select v-model="formDialog.openTarget" filterable placeholder="请选择">
                <el-option
                  v-for="item in MENU.openTarget"
                  :key="item.dictionaryid"
                  :label="item.value"
                  :value="item.dictionaryid">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 10, offset: 0}">
            <el-form-item prop="navigateUrl" label="链接地址">
              <el-input type="text"
                        v-model="formDialog.navigateUrl"
                        placeholder="菜单编码" spellcheck="false" auto-capitalize="off" auto-complete="off" auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 10, offset: 2}">
            <el-form-item prop="img" label="菜单图标">
              <el-input type="text"
                        v-model="formDialog.img"
                        placeholder="菜单编码" spellcheck="false" auto-capitalize="off" auto-complete="off" auto-correct="off"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="description" label="菜单描述">
          <el-input type="textarea"
                    :autosize="{ minRows: 1, maxRows: 2}"
                    v-model="formDialog.description"
                    placeholder="备注" spellcheck="false" auto-capitalize="off" auto-complete="off" auto-correct="off"></el-input>
        </el-form-item>
        <el-form-item class="createTime" prop="createDate" label="创建时间">
          {{formDialog.createDate?formatterTime(formDialog.createDate, 1):formatterTime(new Date(), 1)}}
        </el-form-item>
      </s-form>
      <el-button slot="footer" @click="dialogSave">保存</el-button>
    </s-dialog>
  </div>
</template>

<script>
  import {AutoVue} from '~/plugins/Tools';
  /**
   * 模板思想
   */
  function __form () {
    return {
      createDate: { value: '', rule: [], notes: '创建时间' },
      description: { value: '', rule: [], notes: '菜单描述' },
      id: { value: 0, rule: [], notes: 'id' },
      img: { value: '', rule: [], notes: '图片路径' },
      isShow: { value: true, rule: [], notes: '显示状态 1：显示 2：不显示' },
      menuCode: { value: '', rule: [], notes: '菜单编码' },
      menuLevel: { value: '', rule: [], notes: '菜单级别' },
      menuName: { value: '', rule: [], notes: '菜单名称' },
      menuType: { value: 1, rule: [], dictionary: 'menuType', notes: '菜单类型' },
      navigateUrl: { value: '', rule: [], notes: '链接地址' },
      openTarget: { value: 1, rule: [], dictionary: 'openType', notes: '页面位置' },
      pId: { value: 0, rule: [], notes: '上级菜单id' },
      showOrder: { value: 0, rule: [], notes: '显示顺序' },
      parent: { value: '' },
    };
  }
  export default AutoVue({
    name: 'menu-safety',
    transition: 'slide-fade',
    data: {
      tree: {
        data: [],
        select: {
          id: 0,
          children: [],
          img: 'fa-users',
          menuCode: '',
          menuLevel: '',
          menuName: '',
          menuType: 2,
          navigateUrl: '',
          openTarget: 1,
          pId: -1,
          showOrder: 3,
          show_menuType: '',
          show_openTarget: '',
        },
      },
      dialog: {
        title: '新增',
        saveParameter: {},
        formRef: 'formDialog',
      },
      formDialog: __form(),
      menuUpdate: false,
    },
    store: {
      s: ['CUSTOM_customers', 'USER', 'MENU'],
      g: ['MENU_dictionary'],
    },
    methods: {
      treeContent (h, { node, data, store }) {
        return (
          <span>
            <span>
              <span>{data.menuName}</span>
            </span>
            <span style="float: right; margin-right: 20px">
              <el-button size="mini" type="primary" class={{ 'display': !this.menuUpdate || node.level === 1 }} on-click={ event => this.treeMenuUpdate(event, store, data, -1) }><i class="fa fa-arrow-up" aria-hidden="true"></i></el-button>
              <el-button size="mini" type="danger" class={{ 'display': !this.menuUpdate || node.level === 1 }} on-click={ event => this.treeMenuUpdate(event, store, data, 1) }><i class="fa fa-arrow-down" aria-hidden="true"></i></el-button>
              <el-button size="mini" type="primary" icon="plus" class={{ 'display': this.menuUpdate }} on-click={ event => this.treeAppend(event, store, data) }></el-button>
              <el-button size="mini" type="danger" icon="delete" class={{ 'display': this.menuUpdate || (node.childNodes.length !== 0 || node.level === 1) }} on-click={ event => this.treeRemove(event, store, data) }></el-button>
            </span>
          </span>);
      },
      treeClick (data, node, tree) {
        if (data.menuLevel === '-1') return;
        this.tree.select = data;
      },
      treeAppend (event, store, data) {
        this.dialogOpen('ADD', {store, data});
        event.stopPropagation();
      },
      treeRemove (event, store, data) {
        this.$confirm('您将删除本节点。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        })
          .then(async _ => {
            try {
              await this.post('/menu/delete/', [data.id]);
              store.remove(data);
            } catch (err) {
              console.log(err);
            }
          })
          .catch(_ => {});
        event.stopPropagation();
      },
      treeMenuUpdate (event, store, data, type) {
        this.$confirm(`您将${type === -1 ? '升' : '降'}本节点。`, '确认？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        })
          .then(async _ => {
            try {
              // console.log(store, data);
              let parent = store.nodesMap[data.id + ''].parent;
              let parentNodes = [];

              for (let item of parent.childNodes) {
                parentNodes.push(Object.assign({}, item));
              }
              let stepNodes = [];
              let index = parentNodes.findIndex(function (value, index, arr) {
                return value.data.id === data.id;
              });
              for (let item of parentNodes) {
                stepNodes.push(item.data);
                parent.store.remove(item.data);
              }
              stepNodes[index] = stepNodes.splice(index + type, 1, stepNodes[index])[0];
              for (let item of stepNodes) {
                store.append(item, parent.data);
              }
              await this.post('/menu/updateOrder', {
                id: data.id,
                showOrder: type,
              });
            } catch (err) {
              console.log(err);
            }
          })
          .catch(_ => {});
        event.stopPropagation();
      },
      dialogInit (formRef) {
        let obj = {};
        switch (formRef) {
        case 'formDialog':
          obj = __form();
          break;
        }
        this[formRef] = {
          ...this[formRef],
          ...this.ObjectClone(obj),
        };
        this.resetFields(formRef);
      },
      async dialogOpen (type, more) {
        if (type) {
          type = type.toUpperCase();
        }
        if (!this.DICTIONARY_menu) {
          await this.USE('DICTIONARY_menu');
        }
        switch (type) {
        case 'ADD':
          this.dialog.title = '新增';
          this.dialog.saveParameter = more;
          let {data} = more;
          if (data.menuLevel === '0') {
            this.formDialog.pId = -1;
            this.formDialog.parent = '顶级菜单';
          } else {
            this.formDialog.pId = parseInt(data.id);
            this.formDialog.parent = data.menuName;
          }
          let menuLevel = parseInt(data.menuLevel);
          if (menuLevel === -1) {
            menuLevel = 0;
          }
          this.formDialog.menuLevel = menuLevel + 1 + '';
          this.formDialog.showOrder = data.children.length + 1;
          this.formDialog.id = 0;
          break;
        case 'PUT':
          this.dialog.title = '修改';
          console.log(type, more);
          for (let index in __form()) {
            this.formDialog[index] = this.tree.select[index];
          }
          this.formDialog.isShow = this.formDialog.isShow === 1;
          if (!this.formDialog.parent) {
            if (this.formDialog.pId === -1) {
              this.formDialog.parent = this.USER.app.aName;
            } else {
              this.formDialog.parent = this.$refs.tree.store.nodesMap[this.formDialog.pId + ''].data.menuName;
            }
          }
          break;
        }
        this.dialog.visible = true;
      },
      dialogSave () {
        let more = this.dialog.saveParameter;
        if (this.dialog.title === '新增') {
          this.VALIDATE('formDialog', async (option, diactionary) => {
            option.isShow = option.isShow ? 1 : 2;
            delete option.parent;
            try {
              let {id} = await this.post('/menu/add', option);
              option = {
                ...option,
                id,
                ...diactionary,
                children: [],
              };
              let {store, data} = more;
              store.append(option, data);
              this.dialogInit('formDialog');
              this.dialog.visible = false;
            } catch (err) {
              console.log(err);
            }
          }, this.MENU_dictionary);
        } else {
          this.VALIDATE('formDialog', async (option, diactionary) => {
            option.isShow = option.isShow ? 1 : 2;
            delete option.parent;
            try {
              await this.post('/menu/add', option);
              this.tree.select = {
                ...option,
                ...diactionary,
              };
              this.$refs.tree.store.nodesMap[option.id + ''].data = this.tree.select;
              this.dialogInit('formDialog');
              this.dialog.visible = false;
            } catch (err) {
              console.log(err);
            }
          }, this.MENU_dictionary);
        }
      },
    },
    async mounted () {
      if (this.tree.data.length !== 0) return;
      let app = Object.assign(this.USER.app);
      this.tree.data = [{
        id: 'app' + app.id,
        menuLevel: '-1',
        menuName: app.aName,
        children: Object.assign(await this.get('/menu/')),
      }];
    },
  });
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
  .box-card {
    margin: 20px;
  }
  .el-tag{
    font-size: 14px;
  }
  .createTime{
    margin-bottom: -20px;
    z-index: -1;
    position: relative;
  }
  @media screen and (max-width: 800px) {
    .box-card {
      margin: 0;
    }
    .left{
      border: none;
      border-radius: 0;
      overflow: auto;
      box-shadow: none;
    }
    .createTime{
      margin-bottom: -45px;
    }
  }
</style>

<style lang="scss">

</style>
